package cn.raths.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public class RequestTimeFilter implements GatewayFilter, Ordered {

    /**
    * @Title: filter
    * @Description: 过滤方法
    * @Author: Lynn
    * @Version: 1.0
    * @Date:  2022/7/31 17:43
    * @Parameters: [exchange, chain]
    * @Return reactor.core.publisher.Mono<java.lang.Void>
    */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //开始时间
        exchange.getAttributes().put("COUNT_Start_TIME", System.currentTimeMillis());
        //执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    //开始时间
                    Long startTime = exchange.getAttribute("COUNT_Start_TIME");
                    //结束时间
                    Long endTime=(System.currentTimeMillis() - startTime);
                    if (startTime != null) {
                        log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                        log.info("====================================");
                    }
                })
        );
    }

    // 优先级，数字越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
